import { tokenExceed } from '../utils/token'
const accountInfo = wx.getAccountInfoSync()
import { version } from './config'

const Hosts = {
  dev: 'http://dev.xiongmaodangao.com/delivery',   //开发环境
  pre: 'https://delivery.xiongmaodangao.com/pre/api', //预发布环境
  prod: 'https://delivery.xiongmaodangao.com/prod/api', //线上环境
};

// API_URL为当前的api环境请求地址
function getBaseUrl(){
  const { envVersion } = wx.getAccountInfoSync().miniProgram;
  var baseUrl;
  switch (envVersion) {
    case 'develop':
      baseUrl = `${Hosts.dev}`;
      break;
    case 'trial':
      baseUrl = `${Hosts.dev}`;
      break;
    case 'release':
      baseUrl = `${Hosts.pre}`;
      break;
    default:
      baseUrl = `${Hosts.pre}`;
      break;
  }
  console.log(baseUrl)

  return baseUrl;
}
/**
 * 封装数据请求的方法
 * https://developers.weixin.qq.com/miniprogram/dev/api/network/request/wx.request.html
 * axios
 * 
 * 组件其实就是含有了 视图的 模块
 */
let _loading = false; //定义一个变量来判断是否loading
export function request (options) {
  // 解构赋值 ---  获取用户传递的参数信息
  const { url, method, data, header, isFullUrl } = options;
  const defaultHeader = getDefaultHeader()
  // 加载动画
  if((!_loading) && (options.url !== '/getOrderRefundLogList')){
    wx.showLoading({
      title: '加载中',
    })
    // console.log('options',options.url,options.url == '/getOrderRefundLogList')
    _loading = true;
  }
  // 核心点 异步 A方法请求，B方法调用
  // 回调函数、promise、generator + yield、async+await
  // console.log('options',options)
  return new Promise((resolve, reject) => {
    var baseUrl = getBaseUrl();
    data && (data.version = version)
    // console.log('baseUrl',baseUrl)
    wx.request({
      url: isFullUrl ? url : baseUrl + url,
      data: data || {},
      method: method || 'GET',
      header: Object.assign({}, defaultHeader, header),
      success: (res) => {
        if (res.statusCode !== 200) {
          toast({title: res.data.message})
        }
        const code = res.data && res.data.code
        if (code === 50000) {
          toast({ title: 'token已过期,请重新登录!' })
          tokenExceed()
        } else if (code === 40002) {
          tokenExceed()
        }
        // 异步操作成功调用resolve
        resolve(res)
      },
      fail: (err) => {
        // 异步操作失败调用reject
        reject(err)
      },
      complete: () => {
        // 成功也好，失败也罢，都是已完成
        if(_loading){
          wx.hideLoading()
          _loading = false
        }
        
      }
    })
  })
}
export function toast(options) {
  const { title, icon, duration } = options
  wx.showToast({
    title: title,
    icon: icon || 'none',
    duration: duration || 5000
  })
}

function getDefaultHeader () {
  const token = wx.getStorageSync('token')
  const header = {
    'content-type': 'application/json',
    'token': `${token}`
  }
  return header
}